<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\Device485Model;
use Illuminate\Http\Request;

class DeviceModelController extends Controller
{
    /**
     * @return void
     */
    public function modelList(Request $request)
    {
        $validatedData = $request->validate([
            'page' => 'nullable|integer',
            'pageSize' => 'nullable|integer',
        ]);
        $pageSize = $validatedData['pageSize'] ?? 20; // 默认每页20条记录
        $devices = Device485Model::with(['device'])->paginate($pageSize);
        $data = [
            'page' => $devices->currentPage(),
            'pageSize' => intval($devices->perPage()),
            'rows' => $devices->items(),
            'total' => $devices->total(),
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function modelAdd(Request $request)
    {
        $val = $request->validate(
            [
                "id" => 'nullable',
                'name' => 'required',
                'read_code' => 'nullable',
                'write_code' => 'nullable',
                'baud' => 'nullable',
                'ror_second' => 'nullable',
            ]
        );
        if (!empty($val['id'])) { // 更新逻辑
            $data = Device485Model::find($val['id']);
            $data->fill($val);
            $data->save();
        } else {
            $data = Device485Model::create($val);
        }
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data->id
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function modelDel($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $device = Device485Model::findOrFail($num);
                $device->delete();
            }
        } else {
            $device = Device485Model::findOrFail($ids);
            $device->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }
}
